import {
  getApiChoiceOutAuthLogin,
  getApiChoiceOutPhone,
  getApiChoiceOutAuthBind,
} from '@/api';
import Taro from '@tarojs/taro';
import type { GetApiMarketLoginOutAuthLoginResponse } from '@/api';

type UserInfo = GetApiMarketLoginOutAuthLoginResponse;

/**
 * 获取微信登录code
 */
export const getAuthCode = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    Taro.login({
      success(e) {
        resolve(e.code);
      },
      fail() {
        reject(false);
      },
    });
  });
};

/**
 * 快速登录
 * @param params
 */
export const quickLogin = async (): Promise<UserInfo> => {
  const code = await getAuthCode();
  console.log('code', code);
  // 登录
  const { data }: { data: UserInfo } = await getApiChoiceOutAuthLogin({
    code,
  });

  return data;
};

/**
 * 微信授权获取手机号
 */

export const getPhone = async (code: string): Promise<string | undefined> => {
  const res = await getApiChoiceOutPhone({ code });
  if (res.success) {
    return res.data;
  }
};

/**
 * 微信和手机号绑定
 */

export const bindPhoneAndAccount = async (
  phone: string,
  openId: string,
  name: string,
  marryDate: string,
  sex: string
): Promise<UserInfo> => {
  const res = await getApiChoiceOutAuthBind({
    phone,
    openId,
    name: name || '',
    marryDate,
    sex,
  });

  // API 返回的是 token 字符串，转换为 UserInfo 格式
  return {
    token: res.data,
    openId,
    phone,
    name,
  } as UserInfo;
};
